<template>
  <div class="previewFile">
    <div class="uploadFile" @click="uploadFile">
      <input
        ref="uploadClamp"
        class="uploadFile_input"
        type="file"
        multiple
        @change.stop="fileChange"
        webkitdirectory
        mozdirectory
        directory
      />
      <el-button type="primary">上传文件夹</el-button>
    </div>
    <div class="previewFile_main">
      <el-tree
        class="left_tree"
        :data="treeList"
        :props="defaultProps"
        @node-click="handleNodeClick"
      ></el-tree>
      <div class="right_main">
        <!-- 图片 -->
        <img v-if="imgUrl" :src="imgUrl" alt="" />
        <!-- 视频 -->
        <video v-if="videoUrl" :src="videoUrl" controls></video>
        <!-- 音频 -->
        <audio v-if="audioUrl" :src="audioUrl" controls></audio>
        <!-- 文档 -->
        <iframe v-if="docUrl" :src="docUrl" frameborder="0"></iframe>
        <!-- 文件预览 -->
        <pre ref="textPreview"></pre>
      </div>
    </div>
  </div>
</template>
<script>
import { getUuid } from '@/utils'
export default {
  name: 'PreviewFile',
  data() {
    return {
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      files: [],
      imgUrl: '',
      videoUrl: '',
      audioUrl: '',
      docUrl: '',
    }
  },
  methods: {
    async fileChange(e) {
      const files = Array.from(e.target.files)
      if (!files.length) {
        this.$message.error('请选择文件')
        return
      }
      for (let i = 0; i < files.length; i++) {
        const item = files[i]
        item.uuid = getUuid()
      }
      this.files = files
      const fileList = files.map((m) => ({
        webkitRelativePath: m.webkitRelativePath,
        name: m.name,
        size: m.size,
        type: m.type,
        uuid: m.uuid,
      }))
      const tree = this.handleFolderSelect(fileList)
      this.treeList = tree
      console.log(tree)
    },
    handleFolderSelect(files) {
      let rootFiles = []
      files.forEach((file) => {
        let parts = file.webkitRelativePath.split('/')
        // 移除文件名获取目录路径
        parts.pop()
        // 递归添加文件到树结构
        addFileToTree(rootFiles, parts, file)
      })
      function addFileToTree(tree, parts, file) {
        let current = tree
        for (let part of parts) {
          let dir = current.find((item) => item.name === part)
          if (!dir) {
            dir = { label: part, name: part, children: [] }
            current.push(dir)
          }
          current = dir.children
        }
        current.push({ label: file.name, ...file })
      }
      return rootFiles
    },
    handleNodeClick(data) {
      const imgFormats = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
      const videoFormats = ['mp4', 'avi', 'mov', 'wmv', 'flv']
      const audioFormats = ['mp3', 'wav', 'ogg']
      const docFormats = ['doc', 'docx', 'pdf', 'ppt', 'pptx', 'xls', 'xlsx']
      const txtFormats = [
        'txt',
        'html',
        'js',
        'ts',
        'css',
        'less',
        'scss',
        'json',
        'vue',
        'md'
      ]
      const otherFormats = ['zip', 'rar', '7z']
      this.imgUrl = ''
      this.videoUrl = ''
      this.audioUrl = ''
      this.docUrl = ''
      this.$refs.textPreview.innerHTML = ''
      if (data.uuid) {
        const file = this.files.find((m) => m.uuid === data.uuid)
        const nameList = file.name.split('.')
        const fileType = nameList[nameList.length - 1].toLowerCase()
        if (imgFormats.includes(fileType)) {
          this.imgUrl = URL.createObjectURL(file)
        } else if (videoFormats.includes(fileType)) {
          this.videoUrl = URL.createObjectURL(file)
        } else if (audioFormats.includes(fileType)) {
          this.audioUrl = URL.createObjectURL(file)
        } else if (docFormats.includes(fileType)) {
          this.docUrl = URL.createObjectURL(file)
        } else if (txtFormats.includes(fileType)) {
          this.previewText(file)
        } else if (otherFormats.includes(fileType)) {
          console.log('压缩包')
        } else {
          this.$message.error('不支持的文件格式')
        }
        console.log(file)
      }
    },
    uploadFile() {
      this.$refs.uploadClamp.value = null
      this.$refs.uploadClamp.click()
    },
    previewText(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const text = e.target.result
        this.$refs.textPreview.innerHTML = text
      }
      reader.readAsText(file)
    },
  },
}
</script>
<style lang="less" scoped>
.previewFile {
  &_main {
    display: flex;
    gap: 5px;
    .right_main {
      flex: 1;
      max-width: calc(100% - 205px);
      img,
      video,
      iframe {
        max-width: 100%;
      }
    }
  }
  ::v-deep {
    .uploadFile {
      width: 112px;
      height: 40px;
      position: relative;
      &_input {
        display: none;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        z-index: 2;
      }
    }
    .left_tree {
      width: 200px;
      overflow-x: auto;
    }
  }
}
</style>
